import qs from 'qs';
import axios from 'axios';
import router from '@/routes/router.js';

axios.defaults.timeout = 5000;  // 请求超时
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

const adminRegex = /api\/Admin/i;

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    let adminIndex = config.url.search(adminRegex);
    let token = '';

    if ( adminIndex > -1 ) {
        // admin
        token = localStorage.getItem('admin_token');
        sessionStorage.setItem('token_type','admin_token');
    } else {
        // h5
    }

    if (empty(token)) {
        config.headers['Authorization'] = 'Bearer ' + token;
    }
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function (res) {
    let adminIndex = res.config.url.search(adminRegex);

    if (res.data.code == 401) {
        if (adminIndex > -1) {
            // 后端
            // localStorage.removeItem('admin_token'); // 清除 token
            router.push({name: 'admin_login'});
        } else {
            // 其他端
        }
    }

    if (res.data.code == 402) {
        console.info('%c接口无权限', 'color: #fc4646');
    }

}, function (error) {
    if (empty(error.response)) {
        console.info('%c网络异常，请重试...', 'color: #fcaf24');
    }

    console.error("%c系统出现未知错误,错误信息："+err.response.statusText+"！", 'color: #fc4646');
    // 对响应错误做点什么
    return Promise.reject(error);
})


/**
 * 判断是否为空
 * @author sweeter 2022-01-22
 * @param       {string|array|object} str [description]
 * @return      {boolean} true|false
 */
export function empty(str){
    if (str === '' || str === null || str === undefined || (typeof str === 'object' && Object.keys(str).length === 0)) {
        return true;
    }
    return false;
}

/**
 * Object to String
 * @author sweeter 2022-01-22
 * @param       {object} data [description]
 * @return      {string} [description]
 */
export function qsstr(data) {
    return qs.stringify(data);
}

/**
 * GET 请求
 * @author sweeter 2022-01-22
 * @param       {string} url [description]
 * @param       {Object} params [description]
 */
export function get(url, params) {
    return new Promise((resolve, reject) => {
        axios.get(url, {params: params}).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err.data)
        })
    })
}

/**
 * POST 请求
 * @author sweeter 2022-01-22
 * @param       {string} url [description]
 * @param       {Object} params [description]
 */
export function post(url, params) {
    return new Promise((resolve, reject) => {
        axios.get(url, qs.stringify(params)).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err.data)
        })
    })
}

/**
 * PUT 请求
 * @author sweeter 2022-01-22
 * @param       {string} url [description]
 * @param       {Object} params [description]
 */
export function put(url, params) {
    return new Promise((resolve, reject) => {
        axios.put(url, qs.stringify(params)).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err.data)
        })
    })
}

/**
 * DELETE 请求
 * @author sweeter 2022-01-22
 * @param       {string} url [description]
 * @param       {Object} params [description]
 */
export function delet(url, params) {
    return new Promise((resolve, reject) => {
        axios.delete(url, {params: params}).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err.data)
        })
    })
}

/**
 * UPLOAD FILE 请求
 * @author sweeter 2022-01-22
 * @param       {string} url [description]
 * @param       {Object} params [description]
 */
export function upload(url, params) {
    return new Promise((resolve, reject) => {
        let headers = {headers: {'Content-Type': 'multipart/form-data'}};
        axios.post(url, params, headers).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err.data)
        })
    })
}